<?php

namespace app\admin\controller\vxpay;

use app\common\controller\Backend;
use think\Db;
/**
 * 微信支付
 */
class Alipay extends Backend
{
    
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    
    
    public function _initialize()
    {
        $this->appid = "wx34e9c1335f650c07";
        $this->appsecret = "d41c9d86a8ccccb0667683d5cfdfc288";
        $this->mchid = '1618926160';
    }
    
    public function jsapipay(){
        include_once realpath(__DIR__ ."/../../../../extend/Alipay/alipay-sdk-PHP-4.9.2/aop/AopCertClient.php");
        include_once realpath(__DIR__ ."/../../../../extend/Alipay/alipay-sdk-PHP-4.9.2/aop/request/AlipayTradePrecreateRequest.php");
        
        if( strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') === false ) {

            return $this->view->fetch("ali");
            
        }
        
        $id = $_GET['id'];
        $str = $_GET['str'];
        $info = DB::name("order_prepare")->where("rand",$str)->order("id desc")->find();
        $time = strtotime($info['create_time']);
        if(time()-$time > 3){
            return $this->view->fetch("expire");
        }
    	//②、统一下单
    	$type_v = $_GET['type_v'];
    	if($type_v == 1){
    	    $pay_order = DB::name("order")->where("id",$id)->find();
    	}else{
    	    $pay_order = DB::name("reorder")->where("id",$id)->find();
    	}
        
        //1、execute 使用
        $aop = new \AopCertClient ();
        // $appCertPath = "应用证书路径（要确保证书文件可读），例如：/home/admin/cert/appCertPublicKey.crt";
        $appCertPath = CERT_PATH."appCertPublicKey.crt";
        // $alipayCertPath = "支付宝公钥证书路径（要确保证书文件可读），例如：/home/admin/cert/alipayCertPublicKey_RSA2.crt";
        $alipayCertPath = CERT_PATH."alipayCertPublicKey.crt";
        // $rootCertPath = "支付宝根证书路径（要确保证书文件可读），例如：/home/admin/cert/alipayRootCert.crt";
        $rootCertPath = CERT_PATH."alipayRootCert.crt";
        
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2021002189601389';
        $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEAu73O2zF+vjRZ10U03uWGKDhMkzn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t7n8oUZk8dtJLtXebRZSzbgmL5Q1Wew41+db4JVg26aZAH4WzthE4iZsJmUk167lKSu3Tn2eQ42E9YQq+vaMFmOV5q0hL1ImqFd/nCHSAsnuWipHC1lUCgYBCNl+aTizdg8WIZBpGBCD2sMy3nW43nx4gyC0eyFkhhtC1dXGX/esUAO/TTf85oWrfRPDKLxwFytm2Cw9SS6FBibw8O1AEVjVsXTrbJ/0dnNkAr5U72VuCTwjEzrqozycOHNKPtJC1LWvfaSxyPwxXnXu8oLlb9Us3ffuta5Fm8QKBgQDNHXlNTEBISw9iJX0GgyPutCwrYD0/p2TKj/r/4+7pLHZOtK071MxLqYN0j06GF7MsHi4swUCCuZIR7Jv+X9XLju8mjAn/pXofZ3DVg347dIQmkhOJmPiTnjFfXL60Zoa6pX7f4qLJ6Dw9ddAJiy0pfLgA9E4hhxsxwvK2xPq1gg==';
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);//调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号
        
        $object = new \stdClass();
        // $object->out_trade_no = '20210823010101001c';
        $object->out_trade_no = $pay_order['order_sn'];
        $object->total_amount = 0.01;
        // $object->subject = '测试商品';
        $object->subject = $pay_order['title'];
        $object->timeout_express = '10m';
        $json = json_encode($object);
       
        $request = new \AlipayTradePrecreateRequest();
        $request->setNotifyUrl('https://ceshi.780g.com/api/vxnotify/alipay_notify');
        $request->setBizContent($json);
        $result = $aop->execute ( $request); 
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            header("location:".$result->$responseNode->qr_code);
        } else {
            error_log(date("Y-m-d H:i:s",time())."支付shibai",3,'nohuidiao.log');
        }

        
    }
    
    // public function jsapipay(){
    //     include_once realpath(__DIR__ ."/../../../../extend/Alipay/alipay-sdk-PHP-4.9.2/aop/AopCertClient.php");
    //     include_once realpath(__DIR__ ."/../../../../extend/Alipay/alipay-sdk-PHP-4.9.2/aop/request/AlipayTradePrecreateRequest.php");
        
    //     $id = $_GET['id'];
    //     $str = $_GET['str'];
    //     $info = DB::name("order_prepare")->where("rand",$str)->order("id desc")->find();
    //     $time = strtotime($info['create_time']);
    //     if(time()-$time > 3){
    //         return $this->view->fetch("expire");
    //     }
    // 	//②、统一下单
    // 	$type_v = $_GET['type_v'];
    // 	if($type_v == 1){
    // 	    $pay_order = DB::name("order")->where("id",$id)->find();
    // 	}else{
    // 	    $pay_order = DB::name("reorder")->where("id",$id)->find();
    // 	}
        
    //     //1、execute 使用
    //     $aop = new \AopCertClient ();
    //     // $appCertPath = "应用证书路径（要确保证书文件可读），例如：/home/admin/cert/appCertPublicKey.crt";
    //     $appCertPath = CERT_PATH."appCertPublicKey.crt";
    //     // $alipayCertPath = "支付宝公钥证书路径（要确保证书文件可读），例如：/home/admin/cert/alipayCertPublicKey_RSA2.crt";
    //     $alipayCertPath = CERT_PATH."alipayCertPublicKey.crt";
    //     // $rootCertPath = "支付宝根证书路径（要确保证书文件可读），例如：/home/admin/cert/alipayRootCert.crt";
    //     $rootCertPath = CERT_PATH."alipayRootCert.crt";
        
    //     $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    //     $aop->appId = '2021002189601389';
    //     $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEAu73O2zF+vjRZ10U03uWGKDhMkznNgj0G0A/iSItPvZTxtKZreUS0mNee5Ey0DcXcGYVxSnpslbpTIKivWMa5Oum0MwwRn4McZzhrlgmAZ1baEHuhxDHl1aTp+k6tvMOUuaFDUB75IzPL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1lUCgYBCNl+aTizdg8WIZBpGBCD2sMy3nW43nx4gyC0eyFkhhtC1dXGX/esUAO/TTf85oWrfRPDKLxwFytm2Cw9SS6FBibw8O1AEVjVsXTrbJ/0dnNkAr5U72VuCTwjEzrqozycOHNKPtJC1LWvfaSxyPwxXnXu8oLlb9Us3ffuta5Fm8QKBgQDNHXlNTEBISw9iJX0GgyPutCwrYD0/p2TKj/r/4+7pLHZOtK071MxLqYN0j06GF7MsHi4swUCCuZIR7Jv+X9XLju8mjAn/pXofZ3DVg347dIQmkhOJmPiTnjFfXL60Zoa6pX7f4qLJ6Dw9ddAJiy0pfLgA9E4hhxsxwvK2xPq1gg==';
    //     $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);//调用getPublicKey从支付宝公钥证书中提取公钥
    //     $aop->apiVersion = '1.0';
    //     $aop->signType = 'RSA2';
    //     $aop->postCharset = 'utf-8';
    //     $aop->format = 'json';
    //     $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
    //     $aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
    //     $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号
        
    //     $object = new \stdClass();
    //     // $object->out_trade_no = '20210823010101001b';
    //     $object->out_trade_no = $pay_order['order_sn'];
    //     $object->total_amount = 0.01;
    //     $object->subject = '测试商品';
    //     // $object->buyer_id ='2088102146225135';
    //     $object->timeout_express = '1m';
    //     $json = json_encode($object);
       
    //     $request = new \AlipayTradePrecreateRequest();
    //     $request->setNotifyUrl('https://ceshi.780g.com/api/vxnotify/alipay_notify');
    //     $request->setBizContent($json);
    //     $result = $aop->execute ( $request); 
    //     $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    //     $resultCode = $result->$responseNode->code;
    //     if(!empty($resultCode)&&$resultCode == 10000){
    //         header("location:".$result->$responseNode->qr_code);
    //     } else {
    //         error_log(date("Y-m-d H:i:s",time())."支付shibai",3,'nohuidiao.log');
    //     }

        
    // }
    
    public function chexiao_order(){
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = 'your app_id';
        $aop->rsaPrivateKey = '请填写开发者私钥去头去尾去回车，一行字符串';
        $aop->alipayrsaPublicKey='请填写支付宝公钥，一行字符串';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='GBK';
        $aop->format='json';
        $object = new stdClass();
        $object->trade_no = '2013112611001004680073956707';
        $json = json_encode($object);
        $request = new AlipayTradeCloseRequest();
        $request->setBizContent($json);
        $result = $aop->execute ( $request); 
        
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
        } else {
        echo "失败";
        }
    }
    
    
    
    /**
     * 从证书中提取公钥
     * @param $cert
     * @return mixed
     */
    public function getPublicKey($certPath)
    {
        $cert = file_get_contents($certPath);
        $pkey = openssl_pkey_get_public($cert);
        $keyData = openssl_pkey_get_details($pkey);
        $public_key = str_replace('-----BEGIN PUBLIC KEY-----', '', $keyData['key']);
        $public_key = trim(str_replace('-----END PUBLIC KEY-----', '', $public_key));
        return $public_key;
    }
    
    public function check_outtrade(){
        $trade = $_GET['trade'];
        $v_type = $_GET['v_type'];
        if($v_type == 1){
            $info = DB::name("order")->where("order_sn",$trade)->field("status")->find();
            if($info['status'] == 2 || $info['status'] == 11){
                $code = 1;
            }else{
                $code = 0;
            }
        }else{
            $info = DB::name("reorder")->where("order_sn",$trade)->field("status")->find();
            if($info['status'] == 2){
                $code = 1;
            }else{
                $code = 0;
            }
        }
        
        $data = array(
            'code'=>$code    
        );
        echo json_encode($data);die; 
    }
    
    public function get_jsapi(){
        // 获取token
        // $token_data = file_get_contents('./wechat_token.txt');
        // if (!empty($token_data)) {
        //     $token_data = json_decode($token_data, true);
        // }
        
        // $time  = time() - $token_data['time'];
        // if ($time > 3600) {
            $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $token_res = $this->https_request($token_url);
            $token_res = json_decode($token_res, true);
            $token = $token_res['access_token'];
        
            $data = array(
                'time' =>time(),
                'token' =>$token
            );
            $res = file_put_contents('./wechat_token.txt', json_encode($data));
            if ($res) {
                echo '更新 token 成功';
            }
        // } else {
        //     $token = $token_data['token'];
        // }
        
        // if ($time > 3600) {
            $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
            $ticket_res = $this->https_request($ticket_url);
            $ticket_res = json_decode($ticket_res, true);
            $ticket = $ticket_res['ticket'];
         
            $data = array(
                'time'    =>time(),
                'ticket'  =>$ticket
            );
            $res = file_put_contents('./wechat_ticket.txt', json_encode($data));
            if ($res) {
                echo '更新 ticket 成功';
            }
        // } else {
        //     $ticket = $ticket_data['ticket'];
        // }
        // 进行sha1签名
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        
        // 注意 URL 建议动态获取(也可以写死).
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // 调用JSSDK的页面地址
        // $url = $_SERVER['HTTP_REFERER']; // 前后端分离的, 获取请求地址(此值不准确时可以通过其他方式解决)
         
        $str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
        $sha_str = sha1($str);
        
        
    }
    
    function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    /**
     * 模拟 http 请求
     * @param  String $url  请求网址
     * @param  Array  $data 数据
     */
    function https_request($url, $data = null){
        // curl 初始化
        $curl = curl_init();
        $header = ['User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)','accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9']; //设置一个你的浏览器agent的header
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        // curl 设置
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    
        // 判断 $data get  or post
        if ( !empty($data) ) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
        // 执行
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}